package com.yzg.lock;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author misterWei
 * @create 2020年06月21号:20点42分
 * @mailbox forcontinue@163.com
 */
@Slf4j(topic = "c.ReadWriteLock")
public class ReadWriteLock {

    public static void main(String[] args) {
        DataContainer dataContainer = new DataContainer();
        new Thread(()->{
            dataContainer.read();
        },"t1").start();
        new Thread(()->{
            dataContainer.write("123");
        },"t2").start();

    }

}
@Slf4j(topic = "c.DataContainer")
class DataContainer{
    private volatile Object data;
    private ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.ReadLock r = rw.readLock();
    private ReentrantReadWriteLock.WriteLock w = rw.writeLock();

    @SneakyThrows
    public Object read(){
        // 读锁
        r.lock();
        log.info("获取读锁");
        Thread.sleep(1000L);
        try {
         return data;
        }finally {
            log.info("释放读锁");
            r.unlock();
        }
    }

    public void write(Object data){
        // 读锁
        w.lock();
        log.info("获取写锁");
        try {
           this.data = data;
        }finally {
            log.info("释放写锁");
            w.unlock();
        }
    }
}
